package com.iwithlong.filter.utils;


import com.iwithlong.filter.exceptions.ForwardException;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by liyingdan on 2017/1/4.
 */
public final class ForwardHttpUtils {

    public static String getRequestURI(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();
        if (StringUtils.length(contextPath) > 0) {
            requestURI = StringUtils.substring(requestURI, contextPath.length());
        }
        return requestURI;
    }

    /**
     * 获取对value编码后的queryString
     *
     * @param request
     * @return
     */
    public static String getEncodeQueryString(HttpServletRequest request) {
        if (request.getQueryString() == null) {
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            Enumeration parameterNames = request.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String parameterName = (String) parameterNames.nextElement();
                String value = request.getParameter(parameterName);
                sb.append(parameterName).append("=").append(URLEncoder.encode(value, "utf-8")).append("&");
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            throw new ForwardException("", "对queryString进行encode失败", e);
        }
    }

    /**
     * 获取IP
     *
     * @param request
     * @return
     */
    public static String getRemoteIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Forward-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Forward-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

    /**
     * 获取request中提交的参数
     *
     * @param request
     * @return
     */
    public static Map<String, String> getParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String key = parameterNames.nextElement();
            String value = request.getParameter(key);
            params.put(key, value);
        }
        return params;
    }

    /**
     * 获取request中提交的参数
     *
     * @param request
     * @return
     */
    public static Map<String, String> getParams(HttpServletRequest request, String encryptKey) {
        Map<String, String> params = new HashMap<String, String>();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String key = parameterNames.nextElement();

            if (StringUtils.equalsIgnoreCase("isEncrypt", key) || StringUtils.equalsIgnoreCase("reportId", key)) {
                continue;
            }
            String value = request.getParameter(key);
                try {
                    value = EncryptionUtils.decryptDes(encryptKey, value);
                    value = StringUtils.trim(value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            params.put(key, value);
        }
        return params;
    }

    /**
     * 获取所有headers
     *
     * @param request
     * @return
     */
    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> headers = new HashMap<String, String>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            headers.put(key, value);
        }

        return headers;
    }

    /**
     * 获取cookie
     *
     * @param request
     * @return
     */
    public static Map<String, String> getCookies(HttpServletRequest request) {
        Map<String, String> cookies = new HashMap<String, String>();
        Cookie[] reqCookies = request.getCookies();
        if (reqCookies == null) {
            return cookies;
        }
        for (Cookie cookie : reqCookies) {
            cookies.put(cookie.getName(), cookie.getValue());
        }
        return cookies;
    }
}
